package com.atguigu.gulimall.order.web;

import com.alipay.api.AlipayApiException;
import com.atguigu.gulimall.order.config.AlipayTemplate;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.PayVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

@Controller
public class PayWebController {

    @Autowired
    AlipayTemplate alipayTemplate;

    @Autowired
    OrderService orderService;

    @Autowired
    OrderItemService orderItemService;


    @GetMapping(value = "payOrder",produces = "text/html")
    //通过produces = "text/html"明确告诉浏览器返回的是text/html类型的数据
    @ResponseBody
    public String payOrder(@RequestParam("orderSn") String orderSn ) throws AlipayApiException {
        System.out.println(orderSn);
        PayVo payVo = getPayVo(orderSn);
        String resultHtml = alipayTemplate.pay(payVo);
        System.out.println("========================");
        System.out.println(resultHtml);
        System.out.println("========================");
        return resultHtml;
    }

    private PayVo getPayVo(String orderSn) {
        OrderEntity orderEntity = orderService.getByOrderSn(orderSn);
        PayVo payVo = new PayVo();

        payVo.setOut_trade_no(orderSn);

        BigDecimal payAmount = orderEntity.getPayAmount();
        BigDecimal bigDecimal = payAmount.setScale(2, RoundingMode.UP);
        payVo.setTotal_amount(bigDecimal.toString());

        List<OrderItemEntity> orderItems = orderItemService.getBaseMapper().selectList(
                new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity orderItemEntity = orderItems.get(0);
        payVo.setSubject(orderItemEntity.getSkuName());
        return payVo;
    }

}
